/**
 * Copyright 2016 JustWayward Team
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.songcha.module_bookreader.ui.activity.reader;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import android.text.InputType;
import android.view.KeyEvent;
import android.widget.FrameLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.songcha.library_base.base.BaseActivity;
import com.songcha.library_business.proxy.teenager.TeenagerManager;
import com.songcha.library_common.ui.dialog.InputDialog;
import com.songcha.library_common.util.ProcessUtil;
import com.songcha.module_bookreader.ModuleBookReaderApplication;
import com.songcha.module_bookreader.R;
import com.songcha.module_bookreader.base.Constant;
import com.songcha.module_bookreader.bean.BookMixAToc;
import com.songcha.module_bookreader.bean._Books;
import com.songcha.module_bookreader.bean.ChapterRead;
import com.songcha.module_bookreader.bean.QueryWordBean;
import com.songcha.module_bookreader.bean.support.BookMark;
import com.songcha.module_bookreader.bean.support.ReadTheme;
//import com.songcha.module_bookreader.component.DaggerBookComponent;
import com.songcha.module_bookreader.manager.CacheManager;
import com.songcha.module_bookreader.manager.CollectionsManager;
import com.songcha.module_bookreader.manager.EventManager;
import com.songcha.module_bookreader.manager.SettingManager;
//import com.songcha.bookreader.ui.adapter.BookMarkAdapter;
import com.songcha.module_bookreader.ui.contract.BookReadContract;
//import com.songcha.bookreader.ui.easyadapter.ReadThemeAdapter;
import com.songcha.module_bookreader.ui.presenter.BookReadPresenter;
import com.songcha.module_bookreader.utils.FileUtils;
import com.songcha.module_bookreader.utils.LogUtils;
import com.songcha.module_bookreader.utils.SharedPreferencesUtil;
import com.songcha.module_bookreader.ui.dialog.QueryWordDialog;
import com.songcha.module_bookreader.ui.view.readview.BaseReadView;
import com.songcha.library_business.provider.IOnWordStarProvider;
import com.songcha.library_common.util.StatusBarUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

//import javax.inject.Inject;


import kotlin.jvm.functions.Function0;


/**
 * 小说阅读器
 */
@Deprecated
public class _BookReadActivity extends BaseActivity implements BookReadContract.View, BaseReadView.IOnWordListener , QueryWordDialog.IOnWordStarListener {

    /*@BindView(R2.id.ivBack)
    ImageView mIvBack;*/

   // @BindView(R2.id.flReadWidget)
    FrameLayout flReadWidget;

   /* @BindView(R2.id.llBookReadTop)
    LinearLayout mLlBookReadTop;*/
    /*@BindView(R2.id.tvBookReadTocTitle)
    TextView mTvBookReadTocTitle;*/
    /*@BindView(R2.id.tvBookReadMode)
    TextView mTvBookReadMode;*/
    /*@BindView(R2.id.tvBookReadSettings)
    TextView mTvBookReadSettings;*/
    //@BindView(R2.id.tvBookReadDownload)
    //TextView mTvBookReadDownload;
   /* @BindView(R2.id.tvBookReadToc)
    TextView mTvBookReadToc;*/
   /* @BindView(R2.id.llBookReadBottom)
    LinearLayout mLlBookReadBottom;*/
    /*@BindView(R2.id.rlBookReadRoot)
    RelativeLayout mRlBookReadRoot;
    @BindView(R2.id.tvDownloadProgress)
    TextView mTvDownloadProgress;

    @BindView(R2.id.rlReadAaSet)
    LinearLayout rlReadAaSet;
    @BindView(R2.id.ivBrightnessMinus)
    ImageView ivBrightnessMinus;
    @BindView(R2.id.seekbarLightness)
    SeekBar seekbarLightness;
    @BindView(R2.id.ivBrightnessPlus)
    ImageView ivBrightnessPlus;
    @BindView(R2.id.tvFontsizeMinus)
    TextView tvFontsizeMinus;
    @BindView(R2.id.seekbarFontSize)
    SeekBar seekbarFontSize;
    @BindView(R2.id.tvFontsizePlus)
    TextView tvFontsizePlus;

    @BindView(R2.id.rlReadMark)
    LinearLayout rlReadMark;
    @BindView(R2.id.tvAddMark)
    TextView tvAddMark;
    @BindView(R2.id.lvMark)
    ListView lvMark;

    @BindView(R2.id.cbVolume)
    CheckBox cbVolume;
    @BindView(R2.id.cbAutoBrightness)
    CheckBox cbAutoBrightness;
    @BindView(R2.id.gvTheme)
    GridView gvTheme;

    private View decodeView;*/

    //@Inject
    BookReadPresenter mPresenter;

    private List<BookMixAToc.mixToc.Chapters> mChapterList = new ArrayList<>();
    //private ListPopupWindow mTocListPopupWindow;
    //private TocListAdapter mTocListAdapter;

    private List<BookMark> mMarkList;
    //private BookMarkAdapter mMarkAdapter;

    private int currentChapter = 1;

    /**
     * 是否开始阅读章节
     **/
    private boolean startRead = false;

    //private TTSPlayer mTtsPlayer;
    //private TtsConfig ttsConfig;

    //private BaseReadView mPageWidget;
    private int curTheme = -1;
    private List<ReadTheme> themes;
    //private ReadThemeAdapter gvAdapter;
    private Receiver receiver = new Receiver();
    private IntentFilter intentFilter = new IntentFilter();
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

    public static final String INTENT_BEAN = "recommendBooksBean";
    public static final String INTENT_SD = "isFromSD";

    private _Books.BookBean mBook;
    private String bookId;

    private boolean isAutoLightness = false; // 记录其他页面是否自动调整亮度
    private boolean mIsFromSD = false;
    private String mFontPath="";

    private QueryWordDialog mQueryWordDialog;
    //private static IOnReadActivityListener mListener;
    //用于和主程序组件通信
    private IOnWordStarProvider mOnWordStarProvider=(IOnWordStarProvider)ARouter.getInstance().build("/sakura/WordStarImpl").navigation();
    private List<String> mStarWordList=new ArrayList<>();//收藏单词列表

    //添加收藏需要，所以跳转的时候传递整个实体类
    public static void startActivity(Context context, _Books.BookBean book) {
        startActivity(context, book, false,"");
    }


   /* public  interface IOnReadActivityListener{
        void onStart(Activity activity);
        void onDestory();
    }*/

    @Override
    protected void initOnCreate(@Nullable Bundle savedInstanceState) {
        initStatusBar(savedInstanceState);
        /*DaggerBookComponent.builder()
                .appComponent(ModuleBookReaderApplication.getAppComponent())
                .build()
                .inject(this);*/
        initView(savedInstanceState);

    }

    @Override
    public boolean isNeedShowLoad() {
        return true;
    }

    @Override
    public boolean isImmerseStatusBar() {
        return true;
    }

    public static void startActivity(Context context, _Books.BookBean book, boolean isFromSD, String fontPath) {
        context.startActivity(new Intent(context, _BookReadActivity.class)
                .putExtra(INTENT_BEAN, book)
                .putExtra(INTENT_SD, isFromSD)
                .putExtra("font_path",fontPath));
    }

    @Override
    public int getLayoutId() {
      /*  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);*/
        //statusBarColor = ContextCompat.getColor(this, R.color.reader_menu_bg_color);
        return 0;
        //return R.layout.bookreader_activity_read111;
    }


 /*   @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerBookComponent.builder()
                .appComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void initToolBar() {
    }*/


    public void initData() {
        mBook = (_Books.BookBean) getIntent().getSerializableExtra(INTENT_BEAN);
        bookId = mBook._id;
        mIsFromSD = getIntent().getBooleanExtra(INTENT_SD, false);
        mFontPath = getIntent().getStringExtra("font_path");


        curTheme = SettingManager.getInstance().getReadTheme();




        int fontSizePx = SettingManager.getInstance().getReadFontSize();

        /*if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
            String filePath = Uri.decode(getIntent().getDataString().replace("file://", ""));
            String fileName;
            if (filePath.lastIndexOf(".") > filePath.lastIndexOf("/")) {
                fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf("."));
            } else {
                fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            }

            CollectionsManager.getInstance().remove(fileName);
            // 转存
            File desc = FileUtils.createWifiTranfesFile(fileName);
            FileUtils.fileChannelCopy(new File(filePath), desc);
            // 建立
            mBook = new Books.BookBean();
            mBook.isFromSD = true;
            mBook._id = fileName;
            mBook.title = fileName;

            mIsFromSD = true;
        }*/
       // EventBus.getDefault().register(this);
        //showDialog();


        //设置标题
        //mTvBookReadTocTitle.setText(mBook.title);



        //mTtsPlayer = TTSPlayerUtils.getTTSPlayer();
       // ttsConfig = TTSPlayerUtils.getTtsConfig();

        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);



       /* CollectionsManager.getInstance().setRecentReadingTime(bookId);
        Observable.timer(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        //延迟1秒刷新书架
                        EventManager.refreshCollectionList();
                    }
                });*/
    }



    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        //flReadWidget=findViewById(R.id.flReadWidget);

        StatusBarUtil.fullScreenForever(this);

        initData();

        //hideStatusBar();
        /*decodeView = getWindow().getDecorView();
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLlBookReadTop.getLayoutParams();
        params.topMargin = StatusBarUtil.Companion.getStatusBarHeight(this) - 2;
        mLlBookReadTop.setLayoutParams(params);*/

        //initAASet();

        initPagerWidget();
        mPresenter.attachView(this);
        // 本地小说  直接打开
        if (mIsFromSD) {
            for(int i=1;i<=1;i++){
                BookMixAToc.mixToc.Chapters chapters = new BookMixAToc.mixToc.Chapters();
                chapters.title = mBook.title;
                mChapterList.add(chapters);
                //加入缓存目录
                FileUtils.fileChannelCopy(new File(mBook.path), new File(FileUtils.getChapterPath(mBook._id, i)));
            }

        }

        if (mIsFromSD)
            showChapterRead(null, currentChapter);
       // else
            //mPresenter.getBookMixAToc(bookId, "chapters");
    }





    //private int lastUseTime=TeenagerManager.Companion.getLastUseTime();

    @Override
    protected void onResume() {
        super.onResume();

        checkTeenagerModeUseTime();

    }

    private void checkTeenagerModeUseTime(){
        if(!TeenagerManager.Companion.isTeenagerMode()) return;
        int useTime=(int)(System.currentTimeMillis()/1000)-TeenagerManager.Companion.getLastUseTime();
        TeenagerManager.Companion.addUseTime(useTime);
        if(TeenagerManager.Companion.getUseTime()>=TeenagerManager.MAX_USE_TIME){
            InputDialog dialog=new InputDialog(this);
            dialog.setDialogMsg("请输入青少年模式密码继续使用");
            dialog.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelText("退出");
            dialog.setOnCancelListener(new Function0<Boolean>(){
                @Override
                public Boolean invoke() {
                    ProcessUtil.exitProcess();
                    return false;
                }
            });
            dialog.setOnConfirmListener(new Function0<Boolean>() {
                @Override
                public Boolean invoke() {
                    if(!dialog.getInput().equals("") && dialog.getInput().equals(TeenagerManager.Companion.getTeenagerPwd())){
                        TeenagerManager.Companion.resetUseTime();
                        return true;
                    }
                    //ToastUtil.show("密码不正确");
                    return false;
                }
            });
            dialog.show();
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        //lastUseTime=(int)(System.currentTimeMillis()/1000);
        if(TeenagerManager.Companion.isTeenagerMode()){
            TeenagerManager.Companion.setLastUseTime();
        }

    }

    /***
     * 加载书签
     */
    /*private void initTocList() {
        mTocListAdapter = new TocListAdapter(this, mChapterList, bookId, currentChapter);
        mTocListPopupWindow = new ListPopupWindow(this);
        mTocListPopupWindow.setAdapter(mTocListAdapter);
        mTocListPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mTocListPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mTocListPopupWindow.setAnchorView(mLlBookReadTop);
        mTocListPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mTocListPopupWindow.dismiss();
                currentChapter = position + 1;
                mTocListAdapter.setCurrentChapter(currentChapter);
                startRead = false;
                showDialog();
                readCurrentChapter();
                hideReadBar();
            }
        });
        mTocListPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                gone(mTvBookReadTocTitle);
                //visible(mTvBookReadReading, mTvBookReadCommunity, mTvBookReadChangeSource);
            }
        });
    }*/

    /**
     * 时刻监听系统亮度改变事件
     */
   /* private ContentObserver Brightness = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            //LogUtils.d("BrightnessOnChange:" + ScreenUtils.getScreenBrightnessInt255());

            // if (!ScreenUtils.isAutoBrightness(ReadActivity.this)) {
              //  seekbarLightness.setProgress(ScreenUtils.getScreenBrightness());
            //}
        }
    };*/


    /***
     * 初始化主题，亮度等设置
     */
    /*private void initAASet() {
        curTheme = SettingManager.getInstance().getReadTheme();
        ThemeManager.setReaderTheme(curTheme, mRlBookReadRoot);

        seekbarFontSize.setMax(10);
        //int fontSizePx = SettingManager.getInstance().getReadFontSize(bookId);
        int fontSizePx = SettingManager.getInstance().getReadFontSize();
        int progress = (int) ((ScreenUtil.px2dp(fontSizePx) - 12) / 1.7f);
        seekbarFontSize.setProgress(progress);
        seekbarFontSize.setOnSeekBarChangeListener(new SeekBarChangeListener());

        seekbarLightness.setMax(100);
        seekbarLightness.setOnSeekBarChangeListener(new SeekBarChangeListener());

       // seekbarLightness.setProgress(ScreenUtil.getScreenBrightness());
        //isAutoLightness = ScreenUtil.isAutoBrightness(this);


       // this.getContentResolver().registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS), true, Brightness);

        if (SettingManager.getInstance().isAutoBrightness()) {
            startAutoLightness();
        } else {
            stopAutoLightness();
        }

        cbVolume.setChecked(SettingManager.getInstance().isVolumeFlipEnable());
        cbVolume.setOnCheckedChangeListener(new ChechBoxChangeListener());

        cbAutoBrightness.setChecked(SettingManager.getInstance().isAutoBrightness());
        cbAutoBrightness.setOnCheckedChangeListener(new ChechBoxChangeListener());

        gvAdapter = new ReadThemeAdapter(this, (themes = ThemeManager.getReaderThemeData(curTheme)), curTheme);
        gvTheme.setAdapter(gvAdapter);
        gvTheme.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < themes.size() - 1) {
                    changedMode(false, position);
                } else {
                    changedMode(true, position);
                }
            }
        });
    }*/

    private boolean mIsDrawOnWord=false;

    /***
     * 初始化页面
     */
    private void initPagerWidget() {
        mIsDrawOnWord=mBook.isFromSD && mBook.path.endsWith("_en.txt");
        int style=SharedPreferencesUtil.getInstance().getInt(Constant.FLIP_STYLE, 0);
        setPageWidget(style);

       // mPageWidget.setIsOnDrawWord(isDrawOnWord);
        if(mIsDrawOnWord){
            //mPageWidget.setOnWordListener(this);
            //mPageWidget.setFontPath(mFontPath);
        }

        if(mIsDrawOnWord){
            mStarWordList=mOnWordStarProvider.getStarWordList();
        }

        //注册电量和时间变化广播接收者
        registerReceiver(receiver, intentFilter);

        if (SharedPreferencesUtil.getInstance().getBoolean(Constant.ISNIGHT, false)) {
           // mPageWidget.setTextColor(ContextCompat.getColor(this, R.color.chapter_content_night),
              //      ContextCompat.getColor(this, R.color.chapter_title_night));
        }


        flReadWidget.removeAllViews();
       // flReadWidget.addView(mPageWidget);


    }

    /**
     * 加载章节列表
     *
     * @param list
     */
    @Override
    public void showBookToc(List<BookMixAToc.mixToc.Chapters> list) {
        mChapterList.clear();
        mChapterList.addAll(list);
        readCurrentChapter();
    }

    /**
     * 获取当前章节。章节文件存在则直接阅读，不存在则请求
     */
    public void readCurrentChapter() {
        if (CacheManager.getInstance().getChapterFile(bookId, currentChapter) != null) {
            showChapterRead(null, currentChapter);
        } else {
            mPresenter.getChapterRead(mChapterList.get(currentChapter - 1).link, currentChapter);
        }
    }


   /* public void mergeAllChapterToFile(){
        mPresenter.mergeAllBook(mBook,mChapterList);
    }*/


    /***
     *  加载章节内容
     * @param data
     * @param chapter
     */
    @Override
    public synchronized void showChapterRead(ChapterRead.Chapter data, int chapter) {
        //网络数据则缓存到本地
        if (data != null) {
            CacheManager.getInstance().saveChapterFile(bookId, chapter, data.body,false);
        }

        if (!startRead) {
            startRead = true;
            currentChapter = chapter;
          /*  if (!mPageWidget.isPrepared) {
                mPageWidget.init(curTheme);
            } else {
                mPageWidget.jumpToChapter(currentChapter);
            }*/
           // hideDialog();
        }
    }


    @Override
    public void netError(int chapter) {
        //hideDialog();//防止因为网络问题而出现dialog不消失
        if (Math.abs(chapter - currentChapter) <= 1) {
            //ToastUtil.show(R.string.net_error);
        }
    }

    @Override
    public void showQueryWordDialog(String word) {
       /* CustomDialog.Companion.Builder builder=new CustomDialog.Companion.Builder(this);
        builder.setAnim(com.pansy.library_common.R.style.dialogBottomSlideWindowAnim)
                .setGravity(Gravity.BOTTOM)
                .setWidth(ScreenUtil.getScreenWidth())
                //.setHeight((int)ScreenUtil.dp2px(200))
                .create().show();*/

        mQueryWordDialog=new QueryWordDialog(this,word);
        //mQueryWordDialog.setIsStar();
        mQueryWordDialog.setOnWordStarListener(this);

        mQueryWordDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                mPresenter.queryWordDetail(word);
            }
        });
       /* mQueryWordDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {


            }
        });*/

        if(mStarWordList.contains(word.toLowerCase())){
            mQueryWordDialog.setIsStar(true);
        }

        mQueryWordDialog.show();

    }

    @Override
    public void onQueryWordSuccess(QueryWordBean bean) {
        if(mQueryWordDialog!=null && bean.getData().getEntries()!=null){
            mQueryWordDialog.showWordDetail(bean);
        }
    }

    @Override
    public void onQueryWordError(Throwable e) {
        if(mQueryWordDialog!=null){
            mQueryWordDialog.onQueryWordError();
        }
    }

    @Override
    public void showError() {
        //hideDialog();
    }

    @Override
    public void complete() {
       // hideDialog();
    }

    private synchronized void hideReadBar() {
       /* gone(mTvDownloadProgress, mLlBookReadBottom, mLlBookReadTop, rlReadAaSet, rlReadMark);
        hideStatusBar();
        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);*/
    }

    private synchronized void showReadBar() { // 显示工具栏
       /* visible(mLlBookReadBottom, mLlBookReadTop);
        showStatusBar();
        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);*/
    }

    private synchronized void toggleReadBar() { // 切换工具栏 隐藏/显示 状态
       /* if (isVisible(mLlBookReadTop)) {
            hideReadBar();
        } else {
            showReadBar();
        }*/
    }

    /***************Title Bar*****************/

    /*@OnClick(R2.id.ivBack)
    public void onClickBack() {
        if (mTocListPopupWindow.isShowing()) {
            mTocListPopupWindow.dismiss();
        } else {
            finish();
        }
    }*/

    /***
     * 切换阅读样式
     * @param style
     */
    private void switchFlipStyle(int style){
        setPageWidget(style);
       // mPageWidget.init(curTheme);
        flReadWidget.removeAllViews();
       // flReadWidget.addView(mPageWidget);
        SharedPreferencesUtil.getInstance().putInt(Constant.FLIP_STYLE, style);
    }

    private void setPageWidget(int style){
       /* switch(style){
            case 0:
                mPageWidget = new PageWidget3D(this, bookId, mChapterList, new ReadListener(),mIsDrawOnWord,mFontPath,mIsFromSD);
                break;
            case 1:
                mPageWidget = new OverlappedWidget(this, bookId, mChapterList, new ReadListener(),mIsDrawOnWord,mFontPath,mIsFromSD);
                break;
            case 2:
                mPageWidget = new NoAimWidget(this, bookId, mChapterList, new ReadListener(),mIsDrawOnWord,mFontPath,mIsFromSD);
                break;
        }*/
    }

/*
    @OnClick(R.id.tvBookReadReading)
    public void readBook() {
        gone(rlReadAaSet, rlReadMark);
        ToastUtils.showToast("正在拼命开发中...");
    }
*/

   /* @OnClick(R.id.tvBookReadCommunity)
    public void onClickCommunity() {
        gone(rlReadAaSet, rlReadMark);
        BookDetailCommunityActivity.startActivity(this, bookId, mTvBookReadTocTitle.getText().toString(), 0);
    }*/

   /* @OnClick(R.id.tvBookReadIntroduce)
    public void onClickIntroduce() {
        gone(rlReadAaSet, rlReadMark);
        BookDetailActivity.startActivity(mContext, bookId);
    }*/

   /* @OnClick(R.id.tvBookReadSource)
    public void onClickSource() {
        BookSourceActivity.start(this, bookId, 1);
    }*/

    /***************Bottom Bar*****************/

   /* @OnClick(R2.id.tvBookReadMode)
    public void onClickChangeMode() { // 日/夜间模式切换
        gone(rlReadAaSet, rlReadMark);

        boolean isNight = !SharedPreferencesUtil.getInstance().getBoolean(Constant.ISNIGHT, false);
        changedMode(isNight, -1);
    }*/

    /***
     * 切换日夜间模式
     * @param isNight
     * @param position
     */
    private void changedMode(boolean isNight, int position) {
        try{
            SharedPreferencesUtil.getInstance().putBoolean(Constant.ISNIGHT, isNight);
            //TODO 切换主题会导致界面显示异常和卡顿
            //AppCompatDelegate.setDefaultNightMode(isNight ? AppCompatDelegate.MODE_NIGHT_YES
              //      : AppCompatDelegate.MODE_NIGHT_NO);

            if (position >= 0) {
                curTheme = position;
            } else {
                curTheme = SettingManager.getInstance().getReadTheme();
            }
            //gvAdapter.select(curTheme);

            //mPageWidget.setTheme(isNight ? ThemeManager.NIGHT : curTheme);


           // mPageWidget.setTextColor(ContextCompat.getColor(this, isNight ? R.color.chapter_content_night : R.color.chapter_content_day),
            //        ContextCompat.getColor(this, isNight ? R.color.chapter_title_night : R.color.chapter_title_day));

            /*mTvBookReadMode.setText(getString(isNight ? R.string.book_read_mode_day_manual_setting
                    : R.string.book_read_mode_night_manual_setting));*/
            Drawable drawable = ContextCompat.getDrawable(this, isNight ? R.drawable.ic_menu_mode_day_manual
                    : R.drawable.ic_menu_mode_night_manual);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            //mTvBookReadMode.setCompoundDrawables(null, drawable, null, null);


            //ThemeManager.setReaderTheme(curTheme, mRlBookReadRoot);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

   /* @OnClick(R2.id.tvBookReadSettings)
    public void setting() {
        if (isVisible(mLlBookReadBottom)) {
            if (isVisible(rlReadAaSet)) {
                gone(rlReadAaSet);
            } else {
                visible(rlReadAaSet);
                gone(rlReadMark);
            }
        }
    }*/

    /*@OnClick(R2.id.tvBookReadDownload)
    public void downloadBook() {
        gone(rlReadAaSet);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("缓存多少章？")
                .setItems(new String[]{"后面五十章", "后面全部", "全部"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                DownloadBookService.post(new DownloadQueue(bookId, mChapterList, currentChapter + 1, currentChapter + 50));
                                break;
                            case 1:
                                DownloadBookService.post(new DownloadQueue(bookId, mChapterList, currentChapter + 1, mChapterList.size()));
                                break;
                            case 2:
                                DownloadBookService.post(new DownloadQueue(bookId, mChapterList, 1, mChapterList.size()));
                                break;
                            default:
                                break;
                        }
                    }
                });
        builder.show();
    }*/

   /* @OnClick(R2.id.tvBookMark)
    public void onClickMark() {
        if (isVisible(mLlBookReadBottom)) {
            if (isVisible(rlReadMark)) {
                gone(rlReadMark);
            } else {
                gone(rlReadAaSet);

                updateMark();

                visible(rlReadMark);
            }
        }
    }*/

    /*@OnClick(R2.id.tvBookReadToc)
    public void onClickToc() {
        gone(rlReadAaSet, rlReadMark);
        if (!mTocListPopupWindow.isShowing()) {
            visible(mTvBookReadTocTitle);
            //gone(mTvBookReadReading, mTvBookReadCommunity, mTvBookReadChangeSource);
            mTocListPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            mTocListPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mTocListPopupWindow.show();
            mTocListPopupWindow.setSelection(currentChapter - 1);
            mTocListPopupWindow.getListView().setFastScrollEnabled(true);
        }
    }*/

    /***************Setting Menu*****************/

   /* @OnClick(R2.id.ivBrightnessMinus)
    public void brightnessMinus() {
        int curBrightness = SettingManager.getInstance().getReadBrightness();
        if (curBrightness > 5 && !SettingManager.getInstance().isAutoBrightness()) {
            //seekbarLightness.setProgress((curBrightness = curBrightness - 2));

            //ScreenUtils.saveScreenBrightnessInt255(curBrightness, ReadActivity.this);
        }
    }

    @OnClick(R2.id.ivBrightnessPlus)
    public void brightnessPlus() {
        int curBrightness = SettingManager.getInstance().getReadBrightness();
        if (!SettingManager.getInstance().isAutoBrightness()) {

            // ScreenUtils.saveScreenBrightnessInt255(curBrightness, ReadActivity.this);
        }
    }*/

 /*   @OnClick(R2.id.tvFontsizeMinus)
    public void fontsizeMinus() {
        calcFontSize(seekbarFontSize.getProgress() - 1);
    }

    @OnClick(R2.id.tvFontsizePlus)
    public void fontsizePlus() {
        calcFontSize(seekbarFontSize.getProgress() + 1);
    }*/

   /* @OnClick(R2.id.tvClear)
    public void clearBookMark() {
        SettingManager.getInstance().clearBookMarks(bookId);

        updateMark();
    }*/

    /***************Book Mark*****************/

   /* @OnClick(R2.id.tvAddMark)
    public void addBookMark() {
        int[] readPos = mPageWidget.getReadPos();
        BookMark mark = new BookMark();
        mark.chapter = readPos[0];
        mark.startPos = readPos[1];
        mark.endPos = readPos[2];
        if (mark.chapter >= 1 && mark.chapter <= mChapterList.size()) {
            mark.title = mChapterList.get(mark.chapter - 1).title;
        }
        mark.desc = mPageWidget.getHeadLine();
        if (SettingManager.getInstance().addBookMark(bookId, mark)) {
            ToastUtil.INSTANCE.show("添加书签成功");
            updateMark();
        } else {
            ToastUtil.INSTANCE.show("书签已存在");
        }
    }*/

   /* private void updateMark() {
        if (mMarkAdapter == null) {
            mMarkAdapter = new BookMarkAdapter(this, new ArrayList<BookMark>());
            lvMark.setAdapter(mMarkAdapter);
            lvMark.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    BookMark mark = mMarkAdapter.getData(position);
                    if (mark != null) {
                        mPageWidget.setPosition(new int[]{mark.chapter, mark.startPos, mark.endPos});
                        hideReadBar();
                    } else {
                        ToastUtil.INSTANCE.show("书签无效");
                    }
                }
            });
        }
        mMarkAdapter.clear();

        mMarkList = SettingManager.getInstance().getBookMarks(bookId);
        if (mMarkList != null && mMarkList.size() > 0) {
            Collections.reverse(mMarkList);
            mMarkAdapter.addAll(mMarkList);
        }
    }*/

    /***************Event*****************/

    /*@Subscribe(threadMode = ThreadMode.MAIN)
    public void showDownProgress(DownloadProgress progress) {
        if (bookId.equals(progress.bookId)) {
            if (isVisible(mLlBookReadBottom)) { // 如果工具栏显示，则进度条也显示
                visible(mTvDownloadProgress);
                // 如果之前缓存过，就给提示
                mTvDownloadProgress.setText(progress.message);
            } else {
                gone(mTvDownloadProgress);
            }
        }
    }*/

   /* @Subscribe(threadMode = ThreadMode.MAIN)
    public void downloadMessage(final DownloadMessage msg) {
        if (isVisible(mLlBookReadBottom)) { // 如果工具栏显示，则进度条也显示
            if (bookId.equals(msg.bookId)) {
                visible(mTvDownloadProgress);
                mTvDownloadProgress.setText(msg.message);
                if (msg.isComplete) {
                    mTvDownloadProgress.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            gone(mTvDownloadProgress);
                        }
                    }, 2500);
                }
            }
        }
    }*/

    /**
     * 显示加入书架对话框
     *
     * @param
     */
    /*private void showJoinBookShelfDialog(final Books.BookBean bean) {
        new AlertDialog.Builder(mContext)
                .setTitle(getString(R.string.book_read_add_book))
                .setMessage(getString(R.string.book_read_would_you_like_to_add_this_to_the_book_shelf))
                .setPositiveButton(getString(R.string.book_read_join_the_book_shelf), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        bean.recentReadingTime = FormatUtils.getCurrentTimeString(FormatUtils.FORMAT_DATE_TIME);
                        CollectionsManager.getInstance().add(bean);
                        finish();
                    }
                })
                .setNegativeButton(getString(R.string.book_read_not), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                })
                .create()
                .show();
    }*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
              /*  if (resultCode == RESULT_OK) {
                    BookSource bookSource = (BookSource) data.getSerializableExtra("source");
                    bookId = bookSource._id;
                }*/
                //mPresenter.getBookMixAToc(bookId, "chapters");
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
               /* if (mTocListPopupWindow != null && mTocListPopupWindow.isShowing()) {
                    mTocListPopupWindow.dismiss();
                    //gone(mTvBookReadTocTitle);
                    //visible(mTvBookReadReading, mTvBookReadCommunity, mTvBookReadChangeSource);
                    return true;
                } else*/
              /*  if (isVisible(rlReadAaSet)) {
                    gone(rlReadAaSet);
                    return true;
               *//* } else if (isVisible(mLlBookReadBottom)) {
                    hideReadBar();
                    return true;*//*
                } else*/ if (!CollectionsManager.getInstance().isCollected(bookId)) {
                    //showJoinBookShelfDialog(mBook);
                    //return true;
                }
                break;
            case KeyEvent.KEYCODE_MENU:
                toggleReadBar();
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (SettingManager.getInstance().isVolumeFlipEnable()) {
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (SettingManager.getInstance().isVolumeFlipEnable()) {
                    return true;
                }
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /***
     * 音量键翻页
     */
  /*  @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            if (SettingManager.getInstance().isVolumeFlipEnable()) {
                mPageWidget.nextPage();
                return true;// 防止翻页有声音
            }
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            if (SettingManager.getInstance().isVolumeFlipEnable()) {
                mPageWidget.prePage();
                return true;
            }
        }
        return super.onKeyUp(keyCode, event);
    }*/

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //if (mTtsPlayer.getPlayerState() == TTSCommonPlayer.PLAYER_STATE_PLAYING)
          //  mTtsPlayer.stop();

        EventManager.refreshCollectionIcon();
        EventManager.refreshCollectionList();
       // EventBus.getDefault().unregister(this);

        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
            LogUtils.e("Receiver not registered");
        }


        if (isAutoLightness) {
           // ScreenUtils.startAutoBrightness(ReadActivity.this);
        } else {
          //  ScreenUtils.stopAutoBrightness(ReadActivity.this);
        }

        if (mPresenter != null) {
            mPresenter.detachView();
        }


    }

    @Override
    public boolean isMarkWord(String word) {
        boolean isStar= mStarWordList.contains(word.toLowerCase());
        return isStar;
    }

    @Override
    public void onWordClick(String word) {
        showQueryWordDialog(word);
    }


    @Override
    public void onWordStar(String word) {
        //ToastUtil.INSTANCE.show("收藏:"+word);
        if(!mStarWordList.contains(word.toLowerCase())){
            mStarWordList.add(word.toLowerCase());
        }
        mOnWordStarProvider.onWordStar(word);

       // mPageWidget.updateAll();
    }

    @Override
    public void onWordUnStar(String word) {
        if(mStarWordList.contains(word.toLowerCase())){
            mStarWordList.remove(word.toLowerCase());
        }
        mOnWordStarProvider.onWordUnStar(word);

       // mPageWidget.updateAll();
    }



    /***
     * 阅读器监听
     */
    /*private class ReadListener implements OnReadStateChangeListener {
        *//***
         * 章节预加载
         *//*
        @Override
        public void onChapterChanged(int chapter) {
            LogUtils.i("onChapterChanged:" + chapter);
            currentChapter = chapter;
            //mTocListAdapter.setCurrentChapter(currentChapter);
            // 加载前一节 与 后三节
            for (int i = chapter - 1; i <= chapter + 3 && i <= mChapterList.size(); i++) {
                if (i > 0 && i != chapter
                        && CacheManager.getInstance().getChapterFile(bookId, i) == null) {
                    mPresenter.getChapterRead(mChapterList.get(i - 1).link, i);
                }
            }
        }

        @Override
        public void onPageChanged(int chapter, int page) {
            LogUtils.i("onPageChanged:" + chapter + "-" + page);
        }

        *//***
         * 读取本地章节失败，加载网络章节
         * @param chapter
         *//*
        @Override
        public void onLoadChapterFailure(int chapter,boolean isFromUser,int beginPos,int endPos) {
            LogUtils.i("onLoadChapterFailure:" + chapter);
            startRead = false;
            if (CacheManager.getInstance().getChapterFile(bookId, chapter) == null)
                mPresenter.getChapterRead(mChapterList.get(chapter - 1).link, chapter);
        }

        @Override
        public void onCenterClick() {
            LogUtils.i("onCenterClick");
            toggleReadBar();
        }

        @Override
        public void onFlip() {
            hideReadBar();
        }
    }*/

    /*private class SeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (seekBar.getId() == seekbarFontSize.getId() && fromUser) {
                calcFontSize(progress);
            } else if (seekBar.getId() == seekbarLightness.getId() && fromUser
                    && !SettingManager.getInstance().isAutoBrightness()) { // 非自动调节模式下 才可调整屏幕亮度

               // ScreenUtils.saveScreenBrightnessInt100(progress, ReadActivity.this);
                //SettingManager.getInstance().saveReadBrightness(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }*/

   /* private class ChechBoxChangeListener implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (buttonView.getId() == cbVolume.getId()) {
                SettingManager.getInstance().saveVolumeFlipEnable(isChecked);
            } else if (buttonView.getId() == cbAutoBrightness.getId()) {
                if (isChecked) {
                    startAutoLightness();
                } else {
                    stopAutoLightness();

                    //ScreenUtils.saveScreenBrightnessInt255(ScreenUtils.getScreenBrightnessInt255(), AppUtils.getAppContext());
                }
            }
        }
    }*/

    /***
     * 时间和电量广播接收
     */
    class Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            /*if (mPageWidget != null) {
                if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                    int level = intent.getIntExtra("level", 0);
                    mPageWidget.setBattery(100 - level);
                } else if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
                    mPageWidget.setTime(sdf.format(new Date()));
                }
            }*/
        }
    }

    /*private void startAutoLightness() {
        SettingManager.getInstance().saveAutoBrightness(true);

        // ScreenUtils.startAutoBrightness(ReadActivity.this);
        seekbarLightness.setEnabled(false);
    }*/

   /* private void stopAutoLightness() {
        SettingManager.getInstance().saveAutoBrightness(false);

        // ScreenUtils.stopAutoBrightness(ReadActivity.this);
       // seekbarLightness.setProgress((int) (ScreenUtils.getScreenBrightnessInt255() / 255.0F * 100));
        seekbarLightness.setEnabled(true);
    }*/

   /* private void calcFontSize(int progress) {
        // progress range 1 - 10
        if (progress >= 0 && progress <= 10) {
            //seekbarFontSize.setProgress(progress);
            mPageWidget.setFontSize((int)(12 + 1.7f * progress));
        }
    }*/

}
